/**
 * @module ENV
 * @version 0.0.0
 */

import {
	isApp,
	isWebview,
	isIOS,
	isIPhone,
	isIPad,
	isAndroid,
	isFunction
} from '@jmfe/jm-common'
// import {getSearchProp} from './url';
// import getUrlPara from './getUrlParam'
const Wxappext = require('./wxapi')
export const wxappext = new Wxappext()

let isMiniApp = false
let ready = false
let callList = []
let miniappPms = null

export function callInMini(callBack) {
	if (!isFunction(callBack)) return
	if (ready) {
		callBack(isMiniApp)
	} else {
		callList.push(callBack)
	}
}
// JD APP
wxappext.isWxapp(res => {
	ready = true
	if (res) {
		isMiniApp = res
	}
	if (callList.length > 0) {
		callList.forEach(item => {
			item(res)
		})
		// 情况 callback 队列
		callList = []
	}
})

export const JD = isApp('jd') //是否在京东app
export const XVIEW = isWebview('xview') //是否在xview
export const WX = isApp('wx') //是否在微信
export const QQ = isApp('qq') //是否在qq
export const WEIBO = isApp('weibo') //是否在微博
export const IOS = isIOS() //是否在ios
export const IPHONE = isIPhone() //是否在iPhone
export const IPAD = isIPad() //是否在iPad
export const ANDROID = isAndroid() //是否在android
export const WK = isWebview('wk') //是否在wk
// export const HOME_XVIEW = getSearchProp('app_home_xview') === '1'; //是否在首页xview
export const WQ = WX

export const MINIAPP = () => isMiniApp

/**
 * @returns Promise<bool>
 */
export const miniAppWithPromise = function() {
	if (miniappPms) {
		return miniappPms
	}
	miniappPms = new Promise(resolve => {
		callInMini(resolve)
	})
	return miniappPms
}

export const getEnviroment = () => {
	//  0 app 1 miniapp 2 其他
	if (JD) {
		return 1
	}
	if (MINIAPP()) {
		return 3
	} else if (WX) {
		return 2
	}
	return 4
}

export const IPHONEX =
	/iphone/gi.test(navigator.userAgent) && screen.height / screen.width > 1.95 //是否是刘海屏
/**
 * 使用ua和wxjs双重验证小程序环境
 */
export function isMiniprogram() {
	return (
		/miniprogram/i.test(navigator.userAgent) ||
		window.__wxjs_environment === 'miniprogram'
	)
}
